#include <stdio.h>
#include <windows.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

#define kWindowWidth	1024
#define kWindowHeight	768
#define kNumOfWindows	1
#define kFontName		"simsun.ttc"
#define kFontSize		26
#define kFontSizeSmall		26

extern void ApplicationStart();
SDL_Renderer *renderer[kNumOfWindows] = {NULL};
TTF_Font *font = NULL;
TTF_Font *smallFont = NULL;

int controlKeyCode = 0;

int inputting = 0;
int inputIndex = 0;
char inputBuffer[17];
const char *inputString = NULL;


int main(int argc, char* argv[]){
	SDL_Event event;
	SDL_Window *window[kNumOfWindows] = {NULL};
	char isRunning = 1;
	char keyCodeBase = 0;
	int i;
	
	/* init */
	AllocConsole();
	freopen("CON","w", stdout);
	if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
		return -1;
	if(TTF_Init() < 0)
		return -1;
	for(i=0; i<kNumOfWindows; i++){
		char title[32];
		sprintf(title, "Display %i", i);
		window[i] = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, kWindowWidth, kWindowHeight, SDL_WINDOW_SHOWN);
		if(window[i] == NULL)
			return -1;
		renderer[i] = SDL_CreateRenderer(window[i], -1, SDL_RENDERER_SOFTWARE);
		if(renderer[i] == NULL)
			return -1;
		SDL_SetRenderDrawColor(renderer[i], 0, 0, 0, 255);
	}
	font = TTF_OpenFont(kFontName, kFontSize);
	smallFont = TTF_OpenFont(kFontName, kFontSizeSmall);

	if(font == NULL || smallFont == NULL)
		return -1;
	
	/* start Application */
	ApplicationStart();
	
	/* loop */
	while(isRunning){
		while(SDL_PollEvent(&event)){
			if(event.type == SDL_QUIT){
				isRunning = 0;
			}else if(event.type==SDL_KEYDOWN){
				int key = event.key.keysym.sym;
				if(key==SDLK_ESCAPE){
					isRunning = 0;
				}else if(inputting){
					if(key==SDLK_TAB){
						inputBuffer[inputIndex] = '\0';
						inputString = inputBuffer;
						inputting = 0;
						inputIndex = 0;
						printf("Simulation: End MFK input with: \"%s\".\n", inputString);
					}else if(inputIndex<16){
						inputBuffer[inputIndex++] = key;
					}
				}else{
					switch(key){
						case SDLK_TAB:
							printf("Simulation: Start MFK input.\n");
							inputting = 1;
							break;
						case 'l':
							keyCodeBase = 0x01;
							break;
						case 'r':
							keyCodeBase = 0x06;
							break;
						case 'u':
							keyCodeBase = 0x0b;
							break;
						case 'd':
							keyCodeBase = 0x12;
							break;
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
							controlKeyCode = keyCodeBase + (key - '1');
							break;
					}
				}
			}
		}
	}
	
	/* cleanup */
	for(i=0; i<kNumOfWindows; i++){
		SDL_DestroyWindow(window[i]);
		SDL_DestroyRenderer(renderer[i]);
	}
	TTF_CloseFont(smallFont);
	TTF_CloseFont(font);
	TTF_Quit();
	SDL_Quit();
	
	return 0;
}
